package algorithm.swordoff;

/**
 * 连续子数组的最大和
 */

public class SQ42 {

    public int maxSubArray(int[] nums) {
        if (nums.length == 0) return 0;

        // dp[i]数组的含义是到以nums[i]结尾时最大和
        // 转移方程 dp[i] = Math.max(dp[i-1]+nums[i], nums[i])
        int[] dp = new int[nums.length];
        int max = Integer.MIN_VALUE;

        for (int i = 0; i < nums.length; i++) {
            dp[i] = i == 0 ? nums[0] : Math.max(dp[i-1]+nums[i], nums[i]);
            max = Math.max(max, dp[i]);
        }

        return max;

    }
}
